<?php


namespace App\Controller\App;


use App\Base\BaseController4App;
use App\Entity\OrderCancel;
use App\Entity\Orders;
use App\Entity\User;
use App\Repository\BannerRepository;
use App\Repository\MoneyRepository;
use App\Repository\OrdersRepository;
use App\Repository\SalesCutRepository;
use App\Repository\SalesUserJuanRepository;
use App\Repository\SiteGunRepository;
use App\Repository\SiteOilCategoryRepository;
use App\Repository\SiteOilRepository;
use App\Repository\SiteRepository;
use App\Repository\UserRepository;
use App\Service\MoneyService;
use App\Service\PayService;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/app/order")
 */
class AppOrderController extends BaseController4App
{
    /**
     * @Route("/prepare", name="AppOrderPrepare")
     */
    public function AppOrderPrepare(
        SiteOilRepository $siteOilRepository
        , SiteGunRepository $siteGunRepository
        , SalesCutRepository $salesCutRepository
    )
    {
        $user = $this->needToBeUser();
        $data = [];
        $req = $this->getRequestData();
        $oil = $req["oil"] ?? "";
        $gun = $req["gun"] ?? "";
        $money = $req["money"] ?? "";
        //找到对应数据
        $oilEn = $siteOilRepository->find($oil);
        $gunEn = $siteGunRepository->find($gun);
        //取出所有优惠
        $cuts = $salesCutRepository->findBy(array("isUse" => true), array("price" => "ASC"));
        $curCut = 0;
        foreach ($cuts as $cut) {
            if ($money >= $cut->getPrice() && $cut->getOil()->getId() == $oilEn->getId()) {
                $curCut = $cut->getCut();
            }
        }
        $num = $money / $oilEn->getPriceOrg();
        $onlineCut = $num * ($oilEn->getPriceOrg() - $oilEn->getPriceSale());
        $realCut = $num * $curCut;

        $data["oil"] = $oilEn;
        $data["gun"] = $gunEn;
        $data["money"] = $money;
        $data["num"] = round($num, 2);
        $data["cut"] = round($realCut, 2);
        $data["onlineCut"] = round($onlineCut, 2);

        return $this->json_out(1, "OK", $data);
    }

    /**
     * @Route("/create", name="AppOrderCreate")
     */
    public function AppOrderCreate(
        SiteOilRepository $siteOilRepository
        , SiteGunRepository $siteGunRepository
        , SalesCutRepository $salesCutRepository
        , SalesUserJuanRepository $salesUserJuanRepository
        , MoneyService $moneyService
        , PayService $payService
    )
    {
        $user = $this->needToBeUser();
        $data = [];
        $req = $this->getRequestData();
        $oil = $req["oil"] ?? "";
        $gun = $req["gun"] ?? "";
        $money = $req["money"] ?? "";
        if (!$oil || !$gun || !$money) {
            return $this->json_out(0, "数据异常");
        }
        //找到对应数据
        $oilEn = $siteOilRepository->find($oil);
        $gunEn = $siteGunRepository->find($gun);
        //取出所有优惠
        $cuts = $salesCutRepository->findBy(array("isUse" => true), array("price" => "ASC"));
        $curCut = 0;
        foreach ($cuts as $cut) {
            if ($money >= $cut->getPrice() && $cut->getOil()->getId() == $oilEn->getId()) {
                $curCut = $cut->getCut();
            }
        }
//        $num = $money / $oilEn->getPriceSale();
//        $realCut = $num * $curCut;

        $num = $money / $oilEn->getPriceOrg();
        $onlineCut = $num * ($oilEn->getPriceOrg() - $oilEn->getPriceSale());
        $realCut = $num * $curCut;

        $data["oil"] = $oilEn;
        $data["gun"] = $gunEn;
        $data["money"] = $money;
        $data["num"] = round($num, 2);
        $data["cut"] = round($realCut, 2);
        $data["onlineCut"] = round($onlineCut, 2);

        //加入优惠券减免
        $juan = $req["juan"];
        $userJuan = $salesUserJuanRepository->find($juan);
        $juanCut = 0;
        if ($userJuan) {
            $juanCut = $userJuan->getJuan()->getCut();
        }

        //创建订单
        $payType = $req["payType"] ?? 100;
        $money = round($money,2) ;
        $realCut = round($realCut,2) ;
        $juanCut = round($juanCut,2) ;
        $onlineCut = round($onlineCut,2) ;
        $payReal = round($money - $realCut - $juanCut - $onlineCut,2);
        $order = new Orders();
        $order->setStatus(0)
            ->setUser($user)
            ->setCreateAt(new \DateTime())
            ->setPayReal($payReal)
            ->setPayTotal($money)
            ->setSn(createOrderSn($user->getId()))
            ->setPayType($payType)//100微信支付，500余额支付
            ->setSales([
                'online' => round($onlineCut,2),
                'cut' => round($realCut,2),
                'juan' => round($juanCut,2),
            ])
            ->setInfo([
                "oil" => $oilEn->getName(),
                "gun" => $gunEn->getName(),
                "num" => $data["num"],
                "juan" => $juan,
            ])
            ->setCheckStatus(0)
        ;
        $this->myEm()->persist($order);
        $this->myEm()->flush();

        //根据情况发起支付
        $param["orderId"] = $order->getId();
        $payOrder = $payService->createPayOrder($user, $payReal, null, $param);
        switch ($payType) {
            case 100: //微信支付
                $openid = $user->getOpenid();
//                $payReal = 0.02;
                $data = $payService->createPayParam($payReal, $payType, $payOrder->getSn(), "orders", $openid);
                return $this->json_out(1, "成功发起请求", [
                    "param"=>$data,
                    "order"=>$order
                ]);
                break;
            case 500: //余额支付
                $userMoney = $moneyService->getUserMoney($user);
                $myMoney = $userMoney["yue"];
                if ($myMoney < $money) {
                    return $this->json_out(0, "余额不足");
                } else {
                    $moneyService->mod($user, $money * -1, MoneyService::__MONEY_XIAN_JIN__, 212, "余额消费", []);
                }
                $from = "order";
                $sn = $payOrder->getSn();
                $payService->uniCallBack($sn, $from);
                return $this->json_out(1, "订单支付成功", [
                    "param"=>[],
                    "order"=>$order
                ]);
                break;
            default:
                return $this->json_out(0, "系统异常");
        }
    }


    /**
     * @Route("/my", name="AppOrderMy")
     */
    public function AppOrderMy(
        OrdersRepository $ordersRepository
    )
    {
        $user = $this->needToBeUser();
        $req = $this->getRequestData();
        $type = $req["type"] ?? 0;
        $page = $req["page"] ?? 1;

        if ($type == 1) {//全部
            $cond["status"] = 0;
        }
        if ($type == 2) {//支付
            $cond["status"] = 1;
        }
        if ($type == 3) {//退款和退款中
            $cond["status"] = ['$gte'=>2];
        }
        $cond["user"]=$user;
        $orders = $ordersRepository->findBy($cond, array("id" => "DESC"), 10, $page * 10 - 10);


        return $this->json_out(1, "OK", $orders);
    }

    /**
     * @Route("/info", name="AppOrderInfo")
     */
    public function AppOrderInfo(
        OrdersRepository $ordersRepository
    )
    {
        $user = $this->needToBeUser();
        $req = $this->getRequestData();
        $id = $req["id"] ?? 0;
        $orders = $ordersRepository->find($id);
        $orders = $this->normalize($orders);
        //生成核销二维码
        $qr = $this->generateUrl('Qr',array("code"=>$orders["sn"]));
        $orders["qr"] = $qr;

        return $this->json_out(1, "OK", $orders);
    }

    /**
     * @Route("/cancel", name="AppOrderCancel")
     */
    public function AppOrderCancel(
        OrdersRepository $ordersRepository
    )
    {
        $user = $this->needToBeUser();
        $req = $this->getRequestData();
        $id = $req["id"] ?? 0;
        $orders = $ordersRepository->find($id);

        if ($orders->getStatus() != 1 ) {

            return $this->json_out(0, "订单状态异常");
        }

        $orderCancel = new OrderCancel();
        $orderCancel->setUser($user)
            ->setOrders($orders)
            ->setCreateAt(new \DateTime())
            ->setStatus(0);
        $this->myEm()->persist($orderCancel);
        $this->myEm()->flush();
        //创建修改订单，然后修改订单状态为2
        $orders->setStatus(2);
        $this->myEm()->persist($orders);
        $this->myEm()->flush();


        return $this->json_out(1, "OK", $orders);
    }


    /**
     * @Route("/count", name="AppOrderCount")
     */
    public function AppOrderCount(
        OrdersRepository $ordersRepository
    )
    {
        $user = $this->needToBeUser();
        $data = [];

        $qb = $ordersRepository->createAggregationBuilder();
        $qb->match()
            ->field("user")
            ->references($user)
            ->group()
            ->field("id")
            ->expression('$user')
            ->field("payReal")
            ->sum('$payReal')
            ->field("num")
            ->sum('$info.num')
        ;
        $data = $qb->execute()->toArray();
        $data[0]["payReal"] = $data[0]["payReal"]??0;
        $data[0]["payReal"] = $data[0]["payReal"]?:0;
        $data[0]["num"] = $data[0]["num"]??0;
        $data[0]["num"] = $data[0]["num"]?:0;

        return $this->json_out(1, "OK", $data);
    }


}
